print('hello world')
print('112233445566')
print('master')
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectKBest, f_classif

# 示例数据
data = {
    'age': [25, 30, np.nan, 35, 40],
    'income': [50000, 60000, 55000, np.nan, 70000],
    'gender': ['M', 'F', 'F', 'M', 'M'],
    'purchase_date': ['2025-01-01', '2025-01-15', '2025-02-01', '2025-02-15', '2025-03-01']
}
df = pd.DataFrame(data)

# 1. 处理缺失值
numeric_imputer = SimpleImputer(strategy='median')
df[['age', 'income']] = numeric_imputer.fit_transform(df[['age', 'income']])

# 2. 特征构造：从日期提取特征
df['purchase_date'] = pd.to_datetime(df['purchase_date'])
df['purchase_month'] = df['purchase_date'].dt.month
df['purchase_day'] = df['purchase_date'].dt.day

# 3. 特征编码
categorical_features = ['gender']
numeric_features = ['age', 'income', 'purchase_month', 'purchase_day']

preprocessor = ColumnTransformer(
    transformers=[
        ('num', StandardScaler(), numeric_features),
        ('cat', OneHotEncoder(), categorical_features)
    ])

# 4. 特征选择（假设有目标变量'target'）
# 这里只是示例，实际使用时需要添加目标变量
X = df.drop('purchase_date', axis=1)
# y = df['target']  # 实际使用时需要

# 创建完整管道
pipeline = Pipeline([
    ('preprocessor', preprocessor),
    ('selector', SelectKBest(score_func=f_classif, k=3))  # 选择最好的3个特征
])

# 应用特征工程
X_processed = pipeline.fit_transform(X)  # 实际使用时添加: , y=y

print("原始特征:\n", df)
print("\n处理后的特征矩阵:\n", X_processed)